package control;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import model.Feature;
import interfaces.IFeature;

public class CFeature implements IFeature {
  private CConnection db;
  
  public CFeature(CConnection db) {
	this.db = db;
  }

  @Override
  public boolean create(Feature f) throws SQLException, ClassNotFoundException {
    Statement s = db.getStatement();
	int i = s.executeUpdate("INSERT INTO Feature VALUES (" + f.getFeatureID() + ", '" + f.getDescription() + "', " + f.getColorID());
	return i > 0;
  }

  @Override
  public boolean update(Feature f) throws SQLException, ClassNotFoundException {
	Statement s = db.getStatement();
	int i = s.executeUpdate("UPDATE Feature SET Description = '" + f.getDescription() + "', Color = " + f.getColorID() + " WHERE featureID = " + f.getFeatureID());
	return i > 0;
  }

  @Override
  public boolean delete(Feature f) throws SQLException, ClassNotFoundException {
	Statement s = db.getStatement();
	int i = s.executeUpdate("DELETE FROM Feature WHERE featureID = " + f.getFeatureID());
	return i > 0;
  }

  @Override
  public ArrayList<Feature> retrieveByID(int id) throws SQLException, ClassNotFoundException {
    Statement s = db.getStatement();
    ResultSet res = s.executeQuery("select * from feature where featureID = " + id);
    ArrayList<Feature> features = new ArrayList<Feature>();
    
    while(res.next()) {
      Feature f = new Feature();
      f.setFeatureID(res.getInt("featureID"));
      f.setDescription(res.getString("Description"));
      f.setColorID(res.getInt("color"));
      features.add(f);
    }
    
    return features;
  }

  @Override
  public ArrayList<Feature> retrieveAll() throws SQLException, ClassNotFoundException {
    Statement s = db.getStatement();
    ResultSet res = s.executeQuery("select * from feature");

    ArrayList<Feature> features = new ArrayList<Feature>();
	    
    while(res.next()) {
      Feature f = new Feature();
      f.setFeatureID(res.getInt("featureID"));
      f.setDescription(res.getString("Description"));
      f.setColorID(res.getInt("color"));
      features.add(f);
    }

    return features;
  }
}
